package homework;

import java.sql.*;

public class Test09_query {
    public static void main(String[] args) {
        Connection con = null;
        Statement stm = null;
        ResultSet rs = null;
        try{
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //进行链接
            String url = "jdbc:mysql://localhost:3306/" +
                    "goodsManagement?serverTimezone=GMT%2B8&useSSL=false";
            con = DriverManager.getConnection(url,"root","");
            //写sql语句
            String sql = "select * from goods";
            //执行sql语句
            stm = con.createStatement();
            //执行查询 得到结果集
            rs = stm.executeQuery(sql);
            //处理结果
            while(rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                double price = rs.getDouble("price");
                String address = rs.getString("address");
                System.out.println(id+":"
                        +name+":"
                        +price+":"
                        +address);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                rs = null;
            }
            if(stm!=null){
                try {
                    stm.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                stm = null;
            }
            if(con!=null){
                try {
                    con.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
                con = null;
            }
        }
    }
}
